package com.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.mapper.FeedBackMapper;
import com.myblog.mapper.UserMapper;
import com.myblog.model.FeedBack;
import com.myblog.model.User;
import com.myblog.service.FeedBackService;
import com.myblog.utils.DataMap;
import com.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FeedBackServiceImpl implements FeedBackService {

    @Autowired
    private FeedBackMapper feedBackMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取所有反馈信息并进行分页处理
     * @param rows
     * @param pageNum
     * @return
     */
    @Override
    public DataMap getAllFeedBackBypage(Integer rows, Integer pageNum) {
        //使用page工具进行分页处理
        PageHelper.startPage(pageNum,rows);
        List<FeedBack> feedBacks = feedBackMapper.selectAllFeedBack();
        PageInfo<FeedBack> pageInfo = new PageInfo<>(feedBacks);

        //处理内容信息
        JSONArray jsonArray = new JSONArray();

        for (FeedBack feedBack : feedBacks) {
            JSONObject jsonObject = new JSONObject();
            Integer personId = feedBack.getPersonId();
            String feedBackPerson = userMapper.selectUserNameById(personId);
            jsonObject.put("person",feedBackPerson);
            jsonObject.put("feedbackDate",feedBack.getFeedbackDate());
            jsonObject.put("feedbackContent",feedBack.getFeedbackContent());
            jsonObject.put("contactInfo",feedBack.getContactInfo());
            jsonArray.add(jsonObject);
        }

        JSONObject result = new JSONObject();
        result.put("result",jsonArray);

        //处理分页信息
        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);

        return DataMap.success().setData(result);
    }

    @Override
    public DataMap addFeedBack(FeedBack feedBack,Integer userId) {
        if ((feedBack.getFeedbackContent() == null)){
            feedBack.setFeedbackContent("空");
        }
        TimeUtil timeUtil = new TimeUtil();
        String formatDateForSix = timeUtil.getFormatDateForSix();

        feedBack.setFeedbackDate(formatDateForSix);
        feedBack.setPersonId(userId);

        feedBackMapper.addFeedBack(feedBack);

        return DataMap.success();
    }
}
